package com.hzit.payweb.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.hzit.payweb.config.PayWebConfig;
import com.hzit.payweb.service.IPayNotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;

/**
 * 支付异步回调
 */
@RestController
@RequestMapping("/payNotify")
public class PayNotifyController {

    private Logger logger = LoggerFactory.getLogger(PayNotifyController.class);

    @Autowired
    private PayWebConfig payWebConfig;

    @Autowired
    private IPayNotifyService iPayNotifyService;

    /**
     * 接收支付宝的异步回调,
     * @return
     */
    @RequestMapping("/receive")
    public String receive(HttpServletRequest request, HttpServletResponse response){

        //1.获取支付宝的回调参数
        HashMap<String,String> paramsMap = new HashMap<String,String>();
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()){
           String key = enumeration.nextElement();
           String value = request.getParameter(key);
           paramsMap.put(key,value);
        }
        logger.info("支付宝异步返回参数：{}....",paramsMap);

        //2.签名验证
//        try {
//            boolean flag = AlipaySignature.rsaCheckV1(paramsMap, payWebConfig.getAlipayPubKey(), "utf-8", payWebConfig.getAlipaySignType());//调用SDK验证签名
//            logger.info("支付宝返回参数验签结果为：{}",flag);
//            if (!flag){
//                return "fail";
//            }
//
//        } catch (AlipayApiException e) {
//            logger.error("AlipayApiException",e);
//            return "fail";
//        }

        // 更新支付流水
        String rlt = iPayNotifyService.updateSerial(paramsMap);

        return rlt;
    }


}
